package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.SearchWordManager;
import com.anne.fish.model.SearchWord;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class SearchWordAction extends BaseAction implements Preparable {
    private SearchWordManager searchWordManager;
    private List searchWords;
    private SearchWord searchWord;
    private Long id;
    private String query;

    public void setSearchWordManager(SearchWordManager searchWordManager) {
        this.searchWordManager = searchWordManager;
    }

    public List getSearchWords() {
        return searchWords;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String searchWordId = getRequest().getParameter("searchWord.id");
            if (searchWordId != null && !searchWordId.equals("")) {
                searchWord = searchWordManager.get(new Long(searchWordId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        searchWords = searchWordManager.search(query, SearchWord.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public SearchWord getSearchWord() {
        return searchWord;
    }

    public void setSearchWord(SearchWord searchWord) {
        this.searchWord = searchWord;
    }

    public String delete() {
        searchWordManager.remove(searchWord.getId());
        saveMessage(getText("searchWord.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            searchWord = searchWordManager.get(id);
        } else {
            searchWord = new SearchWord();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (searchWord.getId() == null);

        searchWordManager.save(searchWord);

        String key = (isNew) ? "searchWord.added" : "searchWord.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}